<?php

namespace Common\Model;

use Think\Model;

class OrderGoodsModel extends Model {

    /**
     * 为订单添加商品用于显示
     */
    public function _getGoodsForOrder(&$orderList) {
        if(is_array($orderList) && count($orderList) > 0) {
            $orderIDs = array();
            foreach ($orderList as $value) {
                $orderIDs[] = $value['orderID'];
            }
            $where['orderID'] = array('in',$orderIDs);
            $goodsList = $this->where($where)
                    ->field('goodsID,goodsName,orderID,num,goodsPrice,comtPrice,catName')
                    ->select();
//            dump($this->getLastSql());
//            dump($goodsList);
            if($goodsList) {
                
                foreach ($orderList as $k => $v) {
                    
                    foreach ($goodsList as $k11 => $v11) {
                        if($v11['orderID'] == $v['orderID']) {
                            $orderList[$k]['goodsList'][] = $v11;
                            unset($goodsList[$k11]);
                        }
                    }
                }
                
            } else if($goodsList === false) {
                logErr($this->getLastSql() . '===' .
                        $this->getError() . '==' . 
                        $this->getDbError(),
                        './Public/order_error');
                $orderList = null;
            }
        }
        
//        dump($orderList);
        
    }
    
    /**
     *  获取单个订单
     */
    public function getOrderGoods($id = null, $where = array()) {
        if (!empty($id)) {
            $where['orderID'] = $id;
        }

        $result = $this->where($where)->find();

        return $result;
    }

    /**
     * 获得列表（带基本查询）
     */
    public function getOrderGoodsList($pageNo = 1, $pageSize = 15, $where = array(), $order = array()) {
        $rt = $this->where($where)->page("$pageNo,$pageSize")->order($order)->select();
        return $rt;
    }

    public function getOrderGoodsListLength($where = array()) {
        return $this->where($where)->count();
    }

    /**
     * 添加单个信息
     * @return type
     */
    public function addOrderGoods($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->add();
        }
        return $rt;
    }

    /**
     * 更新信息(注意$data一定要有主键id,若$data为空，则默认是对$_POST数组处理)
     * @return type
     */
    public function updateOrderGoods($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->save();
        }
        return $rt;
    }

    /**
     * 删除
     */
    public function deleteOrderGoods($id) {
        if ($id <= 0) {
            $this->error = "无效ID";
            return false;
        }
        $data = array("isOn" => 0, "updateTime" => time());
        return $this->where("OrderID=$id")->save($data);
    }

}
